var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
const jwt = require('express-jwt');

var indexRouter = require('./routes/index');
var userRouter = require('./routes/user');
var mobileRouter = require('./routes/mobile/index');

// const env = process.env;
// console.log(env.npm_lifecycle_event, 'process.env');

var secretKey = 'my-app-secret-key';
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(
	jwt.expressjwt({ secret: secretKey, algorithms: ['HS256'] }).unless({
		path: [/^\/mobile\/./],
	})
);
app.use(cors());
app.use('/', indexRouter);
app.use('/user', userRouter);
app.use('/mobile', mobileRouter);

/// websocket && http 重置 ///////////////////////////////
const httpServer = require('http').createServer(app);
const { Server } = require('socket.io');

function socketServer(namespace, callback) {
	const io = new Server(httpServer, {
		...(namespace ? { path: `/${namespace}/` } : {}),
		cors: {
			origin: '*',
		},
	});
	io.on('connection', (socket) => {
		console.log('连接成功！');
		callback(socket);
	});
}

socketServer(null, (socket) => {
	socket.send({ aaa: 'value111' });
});

socketServer('socket1', (socket) => {
	socket.send({ bbb: 'socket1' });
});

//////////////////////////////////////

// 错误处理中间件
// catch 404 and forward to error handler
app.use(function (req, res, next) {
	next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
	if (err.name === 'UnauthorizedError') {
		return res.status(401).send({
			status: 401,
			message: '当前登录信息已过期',
		});
	}

	if (err.message === 'jwt expired') {
		return res.status(401).send({
			status: 401,
			message: '当前登录信息已过期',
		});
	}
	res.status(500).send({
		status: 500,
		message: err.message,
	});
});
////////////////////////

module.exports = {
	app,
	httpServer,
	socketServer,
};
